package cn.iocoder.yudao.framework.datapermission.v1;

import cn.iocoder.yudao.framework.common.biz.permission.PermissionCommonApi;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;

import java.util.List;

/**
 * 通用的数据权限自动配置
 *
 * @author 山野羡民（1032694760@qq.com）
 */
@Slf4j
@AutoConfiguration
@ConditionalOnClass(LoginUser.class)
//坑：配置全局懒加载之后 PermissionApi/UniDataPermissionScope 等 Bean 未加载导致不匹配
@ConditionalOnBean(value = {PermissionCommonApi.class, UniDataPermissionScope.class, UniDataPermissionRuleCustomizer.class})
public class UniDataPermissionAutoConfiguration {

    @Bean
    public UniDataPermissionRule uniDataPermissionRule(PermissionCommonApi permissionApi,
                                                       List<UniDataPermissionScope> permissionScopes,
                                                       List<UniDataPermissionRuleCustomizer> customizers) {
        UniDataPermissionRule rule = new UniDataPermissionRuleImpl(permissionApi, permissionScopes);
        customizers.forEach(customizer -> customizer.customize(rule));
        log.debug("[UniDataPermissionRule] init success");
        return rule;
    }

}
